// src/main/java/com/easy/Interceptor/LoginInterceptor.java
package com.easy.Interceptor;

import cn.hutool.json.JSONUtil;
import com.easy.util.Result;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 获取请求的token
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);

        // 白名单路径直接放行（不需要登录验证的路径）
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/login") ||
                requestURI.equals("/") ||
                requestURI.equals("/api/login/captcha") ||
                requestURI.startsWith("/api/user_account") ||
                requestURI.startsWith("/api/password")) { // 添加密码重置相关接口到白名单
            return true;
        }

        // 判断token是否存在且有效
        if(token == null || !TokenUtil.verify(token)) {
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            Result result = new Result(401, "请先登录", null);
            //hutool
            String json = JSONUtil.toJsonStr(result);
            try {
                response.getWriter().write(json);
            } catch (IOException e) {
                // 处理IO异常
                e.printStackTrace();
            }
            return false;
        }
        return true;
    }
}